<?php

namespace App\Models;

use Auth;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class Coupon extends BaseModel
{
    protected $guarded = [];

    protected $appends = ['countdown', 'statusText', 'userHas', 'stopGetAtT', 'endUseAtT', 'startUseAtT'];

    public function getCountdownAttribute(): string
    {
        if (!$this->end_use_at) return '00小时00分00秒';
        return parserDateStr(Carbon::make($this->end_use_at));
    }

    //public function getUnlockPriceAttribute($v): float
    //{
    //    return round($v);
    //}
    //
    //public function getFreePriceAttribute($v): float
    //{
    //    return round($v);
    //}

    public function getStatusTextAttribute(): string
    {
        if ($this->is_active != 1) return '已过期';
        if (Carbon::make($this->end_use_at)->lt(now())) return '已过期';
        if (Auth::guard('api')->check()) {
            $user = Auth::guard('api')->user();
            $log = DB::table('user_coupon')->where('userId', $user->id)->where('couponId', $this->id)->first();
            if ($log) {
                if (is_null($log->useAt)) return '已领取';
                else return '已使用';
            }
        }

        return '未领取';
    }

    public function getUserHasAttribute(): bool
    {
        if (Auth::guard('api')->check()) {
            $exists = DB::table('user_coupon')->where('userId', Auth::guard('api')->user()->id)->where('couponId', $this->id)->exists();
            if ($exists) return true;
        }
        return false;
    }

    /**
     * @return string|null
     */
    public function getStopGetAtTAttribute()
    {
        if (isset($this->stop_get)) return Carbon::make($this->stop_get)->format('m.d H:i');
        return null;
    }

    public function getStartUseAtTAttribute()
    {
        if (isset($this->start_use_at)) return Carbon::make($this->start_use_at)->format('m.d H:i');
        return null;
    }

    public function getEndUseAtTAttribute()
    {
        if (isset($this->end_use_at)) return Carbon::make($this->end_use_at)->format('m.d H:i');
        return null;
    }
}
